package cn.jbolt.core.Interceptor;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.core.base.JBoltMsg;
import cn.jbolt.core.base.config.JBoltConfig;
import cn.jbolt.core.db.util.JBoltTxKit;
import cn.jbolt.core.kit.JBoltControllerKit;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;

/**
 * JBolt 异常处理全局拦截器
 *
 * @ClassName: JBoltExceptionGlobalInterceptor
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2021年6月17日
 */
public class JBoltExceptionGlobalInterceptor implements Interceptor {
	protected static final Log LOG = Log.getLog(JBoltExceptionGlobalInterceptor.class);

	@Override
	public void intercept(Invocation inv) {
		try {
			inv.invoke();
		} catch (Exception e) {
			e.printStackTrace();
			String errorMsg = null;
			if(JBoltConfig.DEV_MODE){
				errorMsg = StrKit.defaultIfBlank(e.getMessage(),JBoltMsg.GLOBAL_EXCEPTION_DEFAULT_ERROR_MSG);
			}else{
				if(StrUtil.containsIgnoreCase(e.getMessage(),"exception")){
					errorMsg = JBoltMsg.GLOBAL_EXCEPTION_DEFAULT_ERROR_MSG;
				}else{
					errorMsg = StrKit.defaultIfBlank(e.getMessage(),JBoltMsg.GLOBAL_EXCEPTION_DEFAULT_ERROR_MSG);
				}
			}
			LOG.error(e.getMessage());
			JBoltControllerKit.renderFail(inv.getController(), errorMsg);
		}finally {
			JBoltTxKit.clear();
		}
	}
}
